import axios from 'axios'

const instance = axios.create({
  timeout: 6000,
  headers: { 'X-Custom-Header': 'foobar' }
});

// 无感刷新相关配置
let isRefreshing = false; // 是否正在刷新token
let failedQueue: Array<{
  resolve: (value?: string | null) => void;
  reject: (reason?: unknown) => void;
}> = []; // 失败的请求队列

// 处理队列中的请求
const processQueue = (error: unknown, token: string | null = null) => {
  failedQueue.forEach(({ resolve, reject }) => {
    if (error) {
      reject(error);
    } else {
      resolve(token);
    }
  });
  
  failedQueue = [];
};

// 刷新token的函数
const refreshToken = async (): Promise<string | null> => {
  try {
    const refreshTokenValue = localStorage.getItem('refreshToken');
    if (!refreshTokenValue) {
      throw new Error('No refresh token available');
    }

    // 这里需要根据你的实际API接口调整
    const response = await axios.post('/api/auth/refresh', {
      refreshToken: refreshTokenValue
    });

    if (response.data && response.data.code === 200) {
      const { accessToken, refreshToken: newRefreshToken } = response.data.data;
      localStorage.setItem('token', accessToken);
      if (newRefreshToken) {
        localStorage.setItem('refreshToken', newRefreshToken);
      }
      return accessToken;
    } else {
      throw new Error(response.data?.msg || 'Token refresh failed');
    }
  } catch (error) {
    // 刷新失败，清除所有token
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    throw error;
  }
};

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  const token = localStorage.getItem('token')
  config.headers.Authorization = 'Bearer ' + token

  // 在发送请求之前做些什么
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  return response.data;
}, async function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  const originalRequest = error.config;
  const status = error?.response?.status;
  const responseData = error?.response?.data;
  
  // 处理401未授权错误 - 实现无感刷新
  if (status === 401 && !originalRequest._retry) {
    // 如果正在刷新token，将请求加入队列
    if (isRefreshing) {
      return new Promise((resolve, reject) => {
        failedQueue.push({ resolve, reject });
      }).then(token => {
        originalRequest.headers.Authorization = 'Bearer ' + token;
        return instance(originalRequest);
      }).catch(err => {
        return Promise.reject(err);
      });
    }

    // 标记正在刷新
    isRefreshing = true;
    originalRequest._retry = true;

    try {
      // 尝试刷新token
      const newToken = await refreshToken();
      
      // 刷新成功，处理队列中的请求
      processQueue(null, newToken);
      
      // 更新原始请求的Authorization头
      originalRequest.headers.Authorization = 'Bearer ' + newToken;
      
      // 重试原始请求
      return instance(originalRequest);
    } catch (refreshError) {
      // 刷新失败，处理队列中的请求
      processQueue(refreshError, null);
      
      // 清除token并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('refreshToken');
      
      // 可以在这里添加路由跳转到登录页的逻辑
      // window.location.href = '/login';
      
      return Promise.resolve({ 
        code: 401, 
        data: null, 
        msg: '登录已过期，请重新登录' 
      });
    } finally {
      isRefreshing = false;
    }
  }
  
  // 根据不同的状态码返回统一的错误格式
  switch (status) {
    case 400:
      return Promise.resolve({ 
        code: 400, 
        data: null, 
        msg: responseData?.msg || '请求参数错误' 
      });
    
    case 403:
      return Promise.resolve({ 
        code: 403, 
        data: null, 
        msg: responseData?.msg || '禁止访问，权限不足' 
      });
    
    case 404:
      return Promise.resolve({ 
        code: 404, 
        data: null, 
        msg: responseData?.msg || '请求的资源不存在' 
      });
    
    case 408:
      return Promise.resolve({ 
        code: 408, 
        data: null, 
        msg: '请求超时，请稍后重试' 
      });
    
    case 409:
      return Promise.resolve({ 
        code: 409, 
        data: null, 
        msg: responseData?.msg || '数据冲突，请检查后重试' 
      });
    
    case 422:
      return Promise.resolve({ 
        code: 422, 
        data: null, 
        msg: responseData?.msg || '数据验证失败' 
      });
    
    case 429:
      return Promise.resolve({ 
        code: 429, 
        data: null, 
        msg: '请求过于频繁，请稍后重试' 
      });
    
    case 500:
      return Promise.resolve({ 
        code: 500, 
        data: null, 
        msg: responseData?.msg || '服务器内部错误' 
      });
    
    case 502:
      return Promise.resolve({ 
        code: 502, 
        data: null, 
        msg: '网关错误' 
      });
    
    case 503:
      return Promise.resolve({ 
        code: 503, 
        data: null, 
        msg: '服务暂时不可用，请稍后重试' 
      });
    
    case 504:
      return Promise.resolve({ 
        code: 504, 
        data: null, 
        msg: '网关超时' 
      });
    
    default:
      // 网络错误或其他未知错误
      if (!status) {
        return Promise.resolve({ 
          code: -1, 
          data: null, 
          msg: '网络连接失败，请检查网络设置' 
        });
      }
      
      // 其他未处理的错误状态码
      return Promise.resolve({ 
        code: status, 
        data: null, 
        msg: responseData?.msg || `请求失败 (${status})` 
      });
  }
});

// 导出一些辅助函数
export const tokenManager = {
  // 设置token
  setTokens: (accessToken: string, refreshToken?: string) => {
    localStorage.setItem('token', accessToken);
    if (refreshToken) {
      localStorage.setItem('refreshToken', refreshToken);
    }
  },
  
  // 获取token
  getAccessToken: () => localStorage.getItem('token'),
  getRefreshToken: () => localStorage.getItem('refreshToken'),
  
  // 清除所有token
  clearTokens: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
  },
  
  // 检查是否有有效的token
  hasValidToken: () => {
    const token = localStorage.getItem('token');
    return !!token;
  }
};

// 手动刷新token的函数（供外部调用）
export const manualRefreshToken = async (): Promise<boolean> => {
  try {
    await refreshToken();
    return true;
  } catch (error) {
    console.error('Manual token refresh failed:', error);
    return false;
  }
};

// 检查token是否即将过期（需要根据你的token格式调整）
export const isTokenExpiringSoon = (token: string): boolean => {
  try {
    // 这里需要根据你的JWT token格式来解析过期时间
    // 示例：假设token是JWT格式
    const payload = JSON.parse(atob(token.split('.')[1]));
    const exp = payload.exp * 1000; // 转换为毫秒
    const now = Date.now();
    const timeUntilExpiry = exp - now;
    
    // 如果token在5分钟内过期，返回true
    return timeUntilExpiry < 5 * 60 * 1000;
  } catch {
    // 如果解析失败，认为token无效
    return true;
  }
};

export default instance